package com.maven.rabbitmq.rpc;

import com.maven.rabbitmq.constant.Constant;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeoutException;

public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("8.135.54.49");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        connectionFactory.setVirtualHost("rabbitmq");

        Connection connection = connectionFactory.newConnection();
        //2. 创建信道
        Channel channel = connection.createChannel();

        // 3. 队列
        channel.queueDeclare(Constant.RPC_QUEUE_1, true, false, false, null);

        // 4. 生成 唯一标识
        String corrId= UUID.randomUUID().toString();
        String queue = channel.queueDeclare().getQueue();
        AMQP.BasicProperties pro=new AMQP.BasicProperties.Builder().correlationId(corrId).replyTo(queue).build();

        // 5. 发送消息
        channel.basicPublish("", Constant.RPC_QUEUE_1, pro, "hello rpc".getBytes());



        // 这里 还需要接收消息
        final BlockingQueue<String> response=new LinkedBlockingQueue<>(1);


        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("执行回调 方法");
                if(properties.getCorrelationId().equals(corrId)) {
                    String msg = new String(body);
                    System.out.println("收到服务器的响应： " + msg);
                    response.offer(msg);
                }
            }
        };

        channel.basicConsume(queue,true,consumer);


        System.out.println(response.peek() != null ? new String(response.poll()) : "");

//        channel.close();
//        connection.close();

    }
}
